import db, {recentPlans} from '../../database/lowDB/connectDb.js';
import {unioformDateTransform,autoIncreamentKey,dateRegex} from '../../utils/index.js'

class recentPlansModel {
    constructor() {
        this.tableName = 'recentPlans';
    }
    
    // 根据用户id和角色id获取近期计划
    async getRecentPlansByUserIdAndRoleCode({userId,roleCode}) {
        return recentPlans.filter(plan => plan.userId === userId && plan.roleCode === roleCode);
    }

    // 新增近期计划  —— 新增单条
    async addRecentPlan(recentPlanData) {
        const {userId, roleCode, planName,deadline } = recentPlanData;
        const newRecentPlan = {
            id: autoIncreamentKey(recentPlans), 
            userId,
            roleCode,
            planName,
            deadline,
            createTime: unioformDateTransform(new Date())
        };
        recentPlans.unshift(newRecentPlan);
        db.write();
        return true;
    }

    // 新增近期计划 —— 批量新增
    async addBatchRecentPlan({userInfo,recentPlanDataList}) {
        const {userId, roleCode} = userInfo;
        let oldLength = recentPlanDataList.length;

        let newRecentPlans = recentPlanDataList.map(data => {
            const {planName, deadline} = data;
            if (!planName || !deadline || !dateRegex.test(deadline)) {
                // 如果计划名称或截止日期为空，或者截止日期格式不正确，则返回 false
                return undefined
            }
            return {
                id: autoIncreamentKey(recentPlans),
                userId,
                roleCode,
                planName,
                deadline,
                createTime: unioformDateTransform(new Date())
            };
        });
        newRecentPlans = newRecentPlans.filter(plan => plan !== undefined);
        if (newRecentPlans.length === oldLength) {
            recentPlans.unshift(...newRecentPlans.reverse());
            db.write();
            return true;
        }
        return false;
    }
}   

export default new recentPlansModel();